import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

/// FileName sqlite_manager
///
/// @Author 陈晓星
/// @Date 2024/6/4 16:21
///
/// @Description 数据库管理类

class SqliteManager {
  /// 单例
  SqliteManager._internal();
  static final SqliteManager shared = SqliteManager._internal();
  factory SqliteManager() => shared;

  /// 数据库名称
  final String _kDatabasePath = "umeng_push_demo.db";

  /// 数据库版本号
  final int _version = 1;

  /// 数据库实例
  Database? database;

  /// 当前数据库是否可用
  bool get isEnable => database != null && database!.isOpen;

  /// 数据库文件路径
  Future<String> dbFilePath() async {
    String dataPath = await getDatabasesPath();
    String path = join(dataPath,_kDatabasePath);
    return path;
  }

  /// 数据库初始化
  Future<void> initDBContext() async {
    String path = await dbFilePath();
    print("===数据库路径：$path");

    database = await openDatabase(
        path,
        version: _version,
        onCreate: _onCreate,
        onUpgrade:_onUpgrade
    );
  }

  /// 创建表
  Future _onCreate(Database db,int version) async {
    await db.transaction((txn) async {
      // 推送消息表
      db.execute('''
CREATE TABLE IF NOT EXISTS push_message(
  -- 推送消息表
 'id' INTEGER PRIMARY KEY AUTOINCREMENT,  -- ID
 'type' INTEGER(0),                       -- 类型 0：普通消息 1：自定义消息
 'deviceToken' TEXT,		                  -- 服务uuid
 'tag' TEXT,	                            -- 读写特征uuid
 'alias' TEXT,	                          -- 通知特征uuid
 'content' TEXT,				                  -- 密钥
 'dateTime' TEXT                          -- 设备码
);
      ''');
      print("___onCreate database done.");
    });
  }

  /// 更新表
  Future _onUpgrade(Database db,int oldVersion,int newVersion) async {
    print("____onUpgrade database: oldVersion:$oldVersion,newVersion:$newVersion");
  }
}